package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

//远程调用  sca-consumer---->sca-provider
@RestController
public class ConsumerController {
    @Autowired
    private RestTemplate loadBalancedRestTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Value("${spring.application.name:8090}")
    private String appName;

    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho1(){
        String url="http://localhost:8081/provider/echo/8090";
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho2(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url=String.format("http://%s:%s/provider/echo/%s", host,port,appName);
        return restTemplate.getForObject(url,String.class);
    }

    @GetMapping("/consumer/doRestEcho3")
    public String doRestEcho3(){
        String url=String.format("http://%s/provider/echo/%s", "sca-provider",appName);
        return loadBalancedRestTemplate.getForObject(url, String.class);
    }

}
